package com.jyh.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @Author JYH
 * @Date 2024/8/22 14:20
 * @Description 专门操作数据的一个工具类
 */
public final class JDBCUtil {
    private JDBCUtil() {
    }
    public static String MYSQL_DRIVER;
    public static String URL;
    public static String USERNAME;
    public static String PASSWORD;
    static {
        try {
            //1.将db.properties文件中的信息读到流中
            InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
            //2.将inputStream流中的信息转载到Properties集合中
            Properties prop = new Properties();
            prop.load(inputStream);
            //遍历集合并将集合中对应的信息赋值给4个成员变量
            MYSQL_DRIVER = prop.getProperty("className");
            URL = prop.getProperty("url");
            USERNAME = prop.getProperty("username");
            PASSWORD = prop.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    static{
        try {
            Class.forName(MYSQL_DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //1.获取连接对象的方法
    public static Connection getConnection(){
        try {
            return DriverManager.getConnection(URL,USERNAME,PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    //2.关闭资源
    public static void close(Statement statement,Connection connection){
        if (statement!=null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //3.关闭资源
    public static void close(ResultSet resultSet, Statement statement, Connection connection){
        if (resultSet!=null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement!=null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
